import 'dart:io';

import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/media_recorder_util.dart';
import 'package:star_author/widgets/cover_widget.dart';
import 'package:star_author/widgets/select_circle_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_video_info/flutter_video_info.dart';
import 'package:get/get.dart';

import '../../config/api.dart';
import '../../utils/utils.dart';
import '../../widgets/base_widget/app_bar/custom_app_bar.dart';
import '../../widgets/button_widget.dart';
import '../../widgets/dialog/dialog_type.dart';
import '../../widgets/dialog/sure_dialog.dart';
import '../../widgets/no_data_widget.dart';
import 'model/live_good_list_entity.dart';

class LocalVideoModel {
  late LiveGoodListData model;
  bool isUpload = false;
  bool isSuccess = false;
  bool isSelect = false;
  double? duration;
  late FileSystemEntity entity;

  LocalVideoModel(
    this.model,
    this.isUpload,
    this.entity,
    this.duration,
    this.isSuccess,
    this.isSelect,
  );
}

class LocalVideoPage extends StatefulWidget {
  const LocalVideoPage({Key? key}) : super(key: key);

  @override
  State<LocalVideoPage> createState() => _LocalVideoPageState();
}

class _LocalVideoPageState extends State<LocalVideoPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
  }

  List<LocalVideoModel> list = [];

  init() async {
    List<FileSystemEntity> fileList = await MediaRecorderUtil.getFileList();
    List<Map> localVideoList =
        SpUtil.getObjectList(MediaRecorderUtil.localKey) ?? [];
    fileList.forEach((element) async {
      String str = element.path;
      int first = str.lastIndexOf('/');
      int last = str.lastIndexOf('.');
      String id = str.substring(first + 1, last);
      int index = localVideoList
          .indexWhere((element) => element['id'].toString() == id);
      final videoInfo = FlutterVideoInfo();
      LiveGoodListData? data = null;
      String videoFilePath = element.path;
      VideoData? info = await videoInfo.getVideoInfo(videoFilePath);
      if (index != -1) {
        Map<String, dynamic> _data = Map.from(localVideoList[index]);
        data = LiveGoodListData.fromJson(_data);
      } else {
        final res = await API.getBackflowDetail(id);
        Map<String, dynamic> _data = res.data;
        data = LiveGoodListData.fromJson(_data);
      }
      setState(() {
        list.add(
          LocalVideoModel(
            data!,
            false,
            element,
            info?.duration,
            false,
            false,
          ),
        );
      });
    });

    if (MediaRecorderUtil.info != null) {
      list.removeWhere(
          (element) => element.entity.path == MediaRecorderUtil.info?.fileName);
      setState(() {});
    }
  }

  //是否管理
  bool is_select = false;

  uploadAllFiles() {
    checkFileToUpload("当前没有录制视频可以上传!");
    CustomToast.show("开始上传");
    int count = 0;
    setState(() {
      is_select = false;
    });
    for (int i = 0; i < list.length; i++) {
      if (list[i].isSelect) {
        setState(() {
          list[i].isUpload = true;
        });
        Future.delayed(Duration(milliseconds: 500 * i), () {
          MediaRecorderUtil.upload(
            list[i].model.id,
            path: list[i].entity.path,
            success: () {
              setState(() {
                list[i].isSuccess = true;
                list.removeAt(i);
                count++;
                if (count >= list.length) {
                  list.clear();
                }
              });
            },
            faild: () {
              setState(() {
                list[i].isSuccess = false;
              });
            },
          );
        });
      }
    }
  }

  //是否全选
  bool is_select_all = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CustomAppBar(
        Text(
          "本地视频",
          style: TextStyle(
            fontSize: 18.sp,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              setState(() {
                is_select = !is_select;
              });
            },
            child: Text(
              is_select ? "完成" : "批量管理",
              style: TextStyle(fontSize: 14.sp, color: UIConstant.color33),
            ),
          )
        ],
      ),
      body: Container(
        child: RefreshIndicator(
          child: list.length == 0
              ? Container(
                  child: NoDataView(
                    height: Get.height,
                  ),
                )
              : ListView.builder(
                  itemBuilder: (context, index) {
                    String secondStr = "";
                    Duration duration =
                        Duration(milliseconds: list[index].duration!.toInt());
                    int second = duration.inSeconds; //秒
                    int minute = duration.inMinutes;
                    int s = second % 60;
                    getMs(count) {
                      return count <= 9
                          ? "0" + count.toString()
                          : count.toString();
                    }

                    if (minute > 0) {
                      secondStr = getMs(minute) + ":" + getMs(s);
                    } else {
                      secondStr = "00:" + getMs(second);
                    }

                    return GestureDetector(
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                        ),
                        height: 84.w,
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(
                              color: Color(0xFFEEEEEE),
                              width: 1,
                            ),
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                if (is_select)
                                  Container(
                                    child: SelectCircleWidget(
                                      callBack: (val) {
                                        setState(() {
                                          list[index].isSelect = val;
                                        });
                                      },
                                      isSelect: list[index].isSelect,
                                    ),
                                    margin: EdgeInsets.only(
                                      right: 12.w,
                                    ),
                                  ),
                                PeopleCoverWidget(
                                  size: 48,
                                  cover:
                                      list[index].model.goods?.cover?.url ?? "",
                                ),
                                SizedBox(
                                  width: 10.w,
                                ),
                                Container(
                                  child: Column(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        "${list[index].model.goods?.serial ?? ""}",
                                        style: TextStyle(
                                          fontSize: 14.sp,
                                          color: UIConstant.color33,
                                        ),
                                      ),
                                      Text(
                                        "${secondStr}",
                                        style: TextStyle(
                                          fontSize: 12.sp,
                                          color: UIConstant.color99,
                                        ),
                                      ),
                                    ],
                                  ),
                                  height: 48.w,
                                ),
                              ],
                            ),
                            if (!is_select)
                              list[index].isSuccess
                                  ? Text(
                                      "上传成功",
                                      style: TextStyle(
                                          fontSize: 16.sp, color: Colors.green),
                                    )
                                  : list[index].isUpload
                                      ? Row(
                                          children: [
                                            Text(
                                              "上传中...",
                                              style: TextStyle(
                                                  fontSize: 16.sp,
                                                  color: UIConstant.color99),
                                            ),
                                            Container(
                                              child: ButtonWidget(
                                                child: Text(
                                                  "取消",
                                                  style: TextStyle(
                                                      fontSize: 14.sp,
                                                      color:
                                                          UIConstant.color33),
                                                ),
                                                type: ButtonType.bdGray,
                                                width: 68,
                                                height: 28,
                                                onPressed: () {
                                                  DialogUtil.showMyDialog(
                                                    dialogType: DialogType
                                                        .cancel_request_dialog,
                                                    rightButtonOnTap: () {
                                                      MediaRecorderUtil.cancel(
                                                          list[index]
                                                              .model
                                                              .id
                                                              .toString());
                                                      setState(() {
                                                        list[index].isUpload =
                                                            false;
                                                        list[index].isSuccess =
                                                            false;
                                                      });
                                                    },
                                                  );
                                                },
                                              ),
                                              margin: EdgeInsets.only(
                                                left: 12.w,
                                              ),
                                            ),
                                          ],
                                        )
                                      : Row(
                                          children: [
                                            ButtonWidget(
                                              child: Text(
                                                "删除",
                                                style: TextStyle(
                                                  fontSize: 14.sp,
                                                  color: UIConstant.colorE02020,
                                                ),
                                              ),
                                              type: ButtonType.bdRed,
                                              width: 68,
                                              height: 28,
                                              onPressed: () {
                                                DialogUtil.showMyDialog(
                                                  dialogType: DialogType
                                                      .delete_local_video,
                                                  param: {
                                                    'title': list[index]
                                                            .model
                                                            .goods
                                                            ?.serial ??
                                                        "",
                                                  },
                                                  rightButtonOnTap: () {
                                                    deleteByFile(
                                                      index,
                                                      () {
                                                        CustomToast.show(
                                                            "删除成功");
                                                        setState(() {
                                                          list.removeAt(index);
                                                        });
                                                      },
                                                    );
                                                  },
                                                );
                                              },
                                            ),
                                            SizedBox(
                                              width: 10.w,
                                            ),
                                            ButtonWidget(
                                              child: Text(
                                                "上传",
                                                style: TextStyle(
                                                    fontSize: 14.sp,
                                                    color: UIConstant.color33),
                                              ),
                                              type: ButtonType.bdGray,
                                              width: 68,
                                              height: 28,
                                              onPressed: () {
                                                setState(() {
                                                  list[index].isUpload = true;
                                                });
                                                MediaRecorderUtil.upload(
                                                    list[index].model.id,
                                                    path: list[index]
                                                        .entity
                                                        .path, success: () {
                                                  setState(() {
                                                    list[index].isSuccess =
                                                        true;
                                                    list.removeAt(index);
                                                  });
                                                }, faild: () {
                                                  CustomToast.show("上传失败");
                                                  setState(() {
                                                    list[index].isUpload =
                                                        false;
                                                    list[index].isSuccess =
                                                        false;
                                                  });
                                                });
                                              },
                                            ),
                                          ],
                                        )
                          ],
                        ),
                      ),
                      onTap: () {
                        if (is_select) {
                          setState(() {
                            list[index].isSelect = !list[index].isSelect;
                          });
                        }
                      },
                    );
                  },
                  itemCount: list.length,
                ),
          onRefresh: () async {
            list = [];
            init();
          },
        ),
      ),
      bottomNavigationBar: is_select
          ? Container(
              height: 50.w,
              width: Get.width,
              padding: EdgeInsets.symmetric(
                horizontal: 12.w,
              ),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: rgba(0, 0, 0, 0.05),
                    offset: Offset(0, -1),
                    blurRadius: 2,
                    spreadRadius: 0,
                  ),
                ],
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    child: Row(
                      children: [
                        Container(
                          child: SelectCircleWidget(
                            callBack: (val) {
                              setState(() {
                                is_select_all = val;
                                selectAll();
                              });
                            },
                            isSelect: is_select_all,
                          ),
                        ),
                        SizedBox(
                          width: 6.w,
                        ),
                        Text(
                          '全选',
                          style: TextStyle(
                              fontSize: 14.sp, color: Color(0xFF666666)),
                        ),
                      ],
                    ),
                    onTap: () {
                      setState(() {
                        is_select_all = !is_select_all;
                        selectAll();
                      });
                    },
                  ),
                  Row(
                    children: [
                      ButtonWidget(
                        child: Text(
                          "批量删除",
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: rgba(51, 51, 51, 1),
                          ),
                        ),
                        type: ButtonType.bdNormal,
                        onPressed: () {
                          batchDelete();
                        },
                        width: 88,
                        height: 36,
                      ),
                      SizedBox(
                        width: 20.w,
                      ),
                      ButtonWidget(
                        child: Text(
                          "批量上传",
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.white,
                          ),
                        ),
                        type: ButtonType.bgOrange,
                        onPressed: () {
                          uploadAllFiles();
                        },
                        width: 88,
                        height: 36,
                      ),
                    ],
                  ),
                ],
              ),
            )
          : Container(
              height: 1,
            ),
    );
  }

  checkFileToUpload(
    String tips,
  ) {
    List deletes = list.where((element) => element.isSelect).toList();
    if (deletes.length == 0) {
      CustomToast.show(tips);
      return;
    }
  }

  //批量删除
  batchDelete() {
    checkFileToUpload("请选择文件后删除!");
    for (int i = list.length - 1; i >= 0; i--) {
      if (list[i].isSelect) {
        File file = File(list[i].entity.path);
        List<Map> localVideoList =
            SpUtil.getObjectList(MediaRecorderUtil.localKey) ?? [];
        localVideoList.removeWhere((element) =>
            element['id'].toString() == list[i].model.id.toString());
        SpUtil.putObjectList(MediaRecorderUtil.localKey, localVideoList);
        if (file.existsSync()) {
          file.deleteSync();
        }
        list.removeAt(i);
      }
    }
    setState(() {
      is_select = false;
    });
  }

  //删除文件
  deleteByFile(int index, Function nextCall) {
    File file = File(list[index].entity.path);
    if (file.existsSync()) {
      file.deleteSync();
      List<Map> localVideoList =
          SpUtil.getObjectList(MediaRecorderUtil.localKey) ?? [];
      localVideoList.removeWhere((element) =>
          element['id'].toString() == list[index].model.id.toString());
      SpUtil.putObjectList(MediaRecorderUtil.localKey, localVideoList);
      nextCall();
    } else {
      CustomToast.show("不存在当前文件");
    }
  }

  //全选
  selectAll() {
    list.forEach((element) {
      if (is_select_all) {
        element.isSelect = true;
      } else {
        element.isSelect = false;
      }
    });
  }
}
